package com.linx.commonlib.viewpager

import android.util.SparseArray
import android.view.View
import android.view.ViewGroup
import androidx.viewpager.widget.PagerAdapter

class CommonViewPagerAdapter(private val titles: Array<CharSequence>,
                             private val builders: (pos: Int) -> View) : PagerAdapter() {

    private val viewCache = SparseArray<View>()

    private fun getItem(pos: Int): View {
        val view = viewCache[pos] ?: builders(pos)
        viewCache.put(pos, view)
        return view
    }

    override fun instantiateItem(container: ViewGroup, position: Int): Any {
        val view = getItem(position)
        container.addView(view)
        return view
    }

    override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
        container.removeView(`object` as View)
    }

    override fun isViewFromObject(view: View, `object`: Any): Boolean {
        return view === `object`
    }

    override fun getCount(): Int {
        return titles.count()
    }
}